package com.diannuo.springboot.configuration;

import org.springframework.beans.TypeMismatchException;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.MissingServletRequestParameterException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.List;

@RestControllerAdvice
public class GlobalExceptionHandler {

	@ExceptionHandler(value = TypeMismatchException.class)
	public String requestTypeMismatch(TypeMismatchException e){
		String msg = "参数类型不匹配,参数" + e.getPropertyName() + "类型应该为" + e.getRequiredType();
		return msg;
	}

	@ExceptionHandler(value = MissingServletRequestParameterException.class)
	public String requestParamMissing(MissingServletRequestParameterException e){
		String msg = "缺少必要参数,参数名称为" + e.getParameterName();
		return msg;
	}

	@ExceptionHandler(value = MethodArgumentNotValidException.class)
	public String requestBodyValid(MethodArgumentNotValidException e){
		BindingResult bindingResult = e.getBindingResult();
		StringBuilder sb=new StringBuilder();
		List<FieldError> fieldErrors = bindingResult.getFieldErrors();
		fieldErrors.forEach(fieldError -> {
			sb.append(fieldError.getField()+":"+fieldError.getDefaultMessage()+"\n");
		});
		return sb.toString();
	}

	@ExceptionHandler(value = Exception.class)
	public String exception(Exception e){
		return e.getMessage();
	}

}
